<?php 
/******************************************************************************************
Use Case name and Id: 2.0 Post Group Ride Event 
by Michael Puzon,  lastupdated March 21, 2010
Class: COIN 71

Functional Specification

The php servlet issues an insert event to the Google Calendar API using the specified user google username and password and data from postride.php page. Upon successful data insertion, data inputted is then outputted in json format. Output errors are also displayed in JSON format.
Before data entry, a check on existing Title with same date and time is done.

Web Master Maintenance:
******************************************************************************************
Web master may update the google username and password used to connect to Google Calendar. The parameters are under the $user and $pass variable.
*/
    
	//parses date from event feed so it can be checked against user submitted date
	function parseDate($fulldate){   
		$yr = substr($fulldate,0,4);
		$mon = substr($fulldate,5,2);
		$day = substr($fulldate,8,2);
		$hr = substr($fulldate,11,2);
		$min = substr($fulldate,14,2);	
		return ($yr . $mon . $day . $hr . $min);
	}

	//this function takes away \n in a string and replaces with n3wline text
	//this is useful in putting multiple fields in a single json field
    function remLine($str){
		return str_replace("\n", " n3wline ", $str);
	}
    
	//outputs the hour in a 24 hr format, taken from time string
	function getHour($time){
		//add 12 hours to hours if pm
		$ampm = substr($time, 6);
		$poscolon = stripos($time, ':');
		$hour = substr($time, 0, $poscolon);
		if ($ampm == 'pm'){
			$hour += 12;			
		}
		return ($hour);
	}
	
	//outputs error message in json format
	function errormsg($errormsg){	
		echo '{ '
			. '"success": false, ' 
     		        . ' "message": "' . $errormsg . '" '
     		     	. ' }';
	}
    
	//outputs time, date and content in json format
	function outputSuccess($time, $date, $content){
		echo 	'{ '
			. '"success": true, ' 
			. '"fields" : [' 
			. '{ "type": "time" , "detail": "' . $time . '" }, '
     		        . '{ "type": "date" , "detail": "' . $date . '" }, '
     		        . '{ "type": "content" , "detail": "' . $content . '" }'
     		     	. '] }';		
	}		

//gets events feed from Google Calendar object and checks against title and
//datetime by user
//returns true if data exists, and false otherwise
//client - Zend_Gdata_ClientLogin object used to connect to google calendar
//title - title input by user
//start - contains date and time by user
function checkExisting($client, $title, $start) {
  
  $gdataCal = new Zend_Gdata_Calendar($client);
  $eventFeed = $gdataCal->getCalendarEventFeed();
  date_default_timezone_set('America/Los_Angeles');	
  foreach ($eventFeed as $event) {
	if ($title == $event->title->text){	
		foreach ($event->when as $when) {		    
			if ((parseDate($when->startTime)) == $start){
				return true;
			}
		}
	}
  }
  return false;
}

//calls insertEvent using Google Calendar object with content from postride.php
//calls outputSuccess on completion of data entry
//gcal - Zend_Gdata_ClientLogin object used to connect to google calendar
//title - title input by user
//start, time, date - contains date and time by user
function postEvent($gcal, $title, $start, $time, $date){
       	
	$content = "Ride Leader: " . $_POST['leadername'] . "\n" . 
	        "Contact Details: " . $_POST['contact'] . "\n" . 
	        "Ride Rating: " . $_POST['rating'] . "\n";
			
	if (!empty($_POST['desc'])){
		$content .= "Additional Details: " . $_POST['desc'];
	}
	
      // construct event object
      // save to server      
    try {
        $event = $gcal->newEventEntry();        
        $event->title = $gcal->newTitle($title);        
        $when = $gcal->newWhen();
        $when->startTime = $start;

        $event->when = array($when);                    
        $event->where = array($gcal->newWhere($_POST['location']));       
        $event->content = $gcal->newContent($content);
        
        $gcal->insertEvent($event);
        
    }catch (Zend_Gdata_App_Exception $e) {        
        errormsg($e->getResponse());
    }
    //output response in json format to caller
    outputSuccess($time, $date, remLine($content));
}
	
//main body function
//validate user input
 if (empty($_POST['date'])) {
	errormsg('Insufficient Data provided to create event');
    die();
}       
    // load ZEND Google Calendar classes
    require_once 'Zend/Loader.php';
    Zend_Loader::loadClass('Zend_Gdata');
    Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
    Zend_Loader::loadClass('Zend_Gdata_Calendar');
    Zend_Loader::loadClass('Zend_Http_Client');
      
    // connect to Google Calendar service
    $gcal = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
    $user = "biking2010@gmail.com";
    $pass = "foothill2010";
    $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $gcal);
    $gcal = new Zend_Gdata_Calendar($client);
      
	//initialize variables from POST data
	$title = htmlentities($_POST['title']);     
       
	$time = $_POST['time'];
	$min = substr($time, 3, 2);
	$hour = getHour($time);
        
    $date = $_POST['date'];
	$mon = substr($date, 0, 2);
    $day = substr($date, 3, 2);
    $year = substr($date, 6);
        
    if (!checkdate($mon, $day, $year)) {
        errormsg('Invalid start date/time');
		die();        
    } 
	date_default_timezone_set('America/Los_Angeles');
    $start = date(DATE_ATOM, mktime($hour, $min, 0, $mon, $day, $year));
	$whendate = date("Ymdhi", mktime($hour, $min, 0, $mon, $day, $year));
	
	if (checkExisting($client, $title, $whendate)){
		errormsg('Existing Event with Same Title and date/time already exists');
		die();
	}
    postEvent($gcal, $title, $start, $time, $date);      
?>


